package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.HibernateException;

import dao.AgenteDao;
import dao.DaoException;
import dominio.Agente;

import negocio.CommandFacade;
import negocio.ConstantesComando;
import negocio.ContratarAgenteCommand;
import negocio.NegocioException;

/**
 * Servlet implementation class CadastrarAgenteServlet
 */
public class CadastrarAgenteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String agente = request.getParameter("agente");
		
		agente = agente.split("\n")[0];
		
		CommandFacade c = new CommandFacade();
		c.setCmd(ConstantesComando.CONTRATAR_AGENTE);
		
		AgenteDao ad = new AgenteDao();
		try {
			Agente ag = ad.findAgenteByNome(agente);
			c.execute(ag, request);
			response.getWriter().print("Sucesso");
		} catch (HibernateException e) {
			response.getWriter().print("erro");
			e.printStackTrace();
		} catch (DaoException e) {
			response.getWriter().print("erro");
			e.printStackTrace();
		} catch (NegocioException e) {
			response.getWriter().print(e.getMessage());
		}
		finally {
			response.getWriter().flush();
			response.getWriter().close();
		}
		
	}

}
